import { app, BrowserWindow, ipcMain } from "electron";
// import { app, BrowserWindow, ipcMain, IpcMainEvent } from "electron";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { join } from "node:path";
import path from "node:path";
import {initIpcDemo} from './main/ipcDemo'

// 初始化ipc通信Demo
initIpcDemo();

const require = createRequire(import.meta.url);

console.log(`Version: ${require}`);
const __dirname = path.dirname(fileURLToPath(import.meta.url));

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, "..");
process.env.DIST_ELECTRON = join(__dirname, "..");
process.env.DIST = join(process.env.DIST_ELECTRON, "../dist");
process.env.PUBLIC = process.env.VITE_DEV_SERVER_URL
  ? join(process.env.DIST_ELECTRON, "../public")
  : process.env.DIST;

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
export const MAIN_DIST = path.join(process.env.APP_ROOT, "dist-electron");
export const RENDERER_DIST = path.join(process.env.APP_ROOT, "dist");

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL
  ? path.join(process.env.APP_ROOT, "public")
  : RENDERER_DIST;

let win: BrowserWindow | null;
// Here, you can also use other preload
const preload = join(__dirname, "../preload/index.js");
const url = process.env.VITE_DEV_SERVER_URL;
const indexHtml = join(process.env.DIST, "index.html");

function createWindow() {
  win = new BrowserWindow({
    width: 1520,
    height: 700, // 可以设置一个初始高度，用户后续可以调整
    minWidth: 1520, // 设置窗口的最小宽度，以确保宽度不小于固定宽度
    maxWidth: 1520, // 设置窗口的最小宽度，以确保宽度不小于固定宽度
    maxHeight: 700, // 设置窗口的最大高度，以确保高度不大于固定高度
    minHeight: 700, // 设置窗口的最小高度，以确保高度不小于固定高度
    resizable: true, // 防止用户调整窗口大小
    icon: path.join(process.env.VITE_PUBLIC, "electron-vite.svg"),
    webPreferences: {
      devTools: true,
      contextIsolation: true,
      preload: path.join(__dirname, "preload.mjs"),
      nodeIntegration: true
    },
  });

  // Test active push message to Renderer-process.
  win.webContents.on("did-finish-load", () => {
    win?.webContents.send("main-process-message", new Date().toLocaleString());
  });

  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL);
  } else {
    // win.loadFile('dist/index.html')
    win.loadFile(path.join(RENDERER_DIST, "index.html"));
  }
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
    win = null;
  }
});

app.on("activate", () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

/**
 * 新建一个窗口
 * route=>路由地址  paramJsonStr => 序列化后的参数对象
 */
ipcMain.handle("open-win", (_, route: string, paramJsonStr: string) => {
  let childWindow: BrowserWindow | null = null;

  childWindow = new BrowserWindow({
    webPreferences: {
      preload,
      nodeIntegration: true,
      contextIsolation: false,
    },
  });
  const paramData = paramJsonStr ? "?urlParamData=" + paramJsonStr : "";
  if (process.env.VITE_DEV_SERVER_URL) {
    childWindow.loadURL(`${url}#${route}${paramData}`);
  } else {
    childWindow.loadFile(indexHtml, { hash: route + paramData });
  }
  childWindow.on("closed", () => {
    // 在窗口对象被关闭时，取消订阅所有与该窗口相关的事件
    if (childWindow !== null) {
      childWindow.removeAllListeners();
      childWindow = null;
    }
  });
});


/**
 * show : ture 显示app进度条，false，关闭显示
 */
let progressInterval: any;
ipcMain.handle("show-process", (_, show: boolean) => {
// ipcMain.handle("show-process", (event, show: boolean) => {
  const INCREMENT = 0.03;
  const INTERVAL_DELAY = 100; // ms

  let c = 0;
  if (show) {
    progressInterval = setInterval(() => {
      win?.setProgressBar(c);
      if (c < 2) {
        c += INCREMENT;
      } else {
        c = -INCREMENT * 5;
      }
    }, INTERVAL_DELAY);
  } else {
    c = 0;
    win?.setProgressBar(c);
    if (progressInterval) {
      clearInterval(progressInterval);
    }
  }
});

let number = 1;
setInterval(() => {
  if (win && win.webContents) {
    win.webContents.send("event-from-main", "计数" + number++);
  }
}, 2000);


/**语言修改同步 */
ipcMain.handle("lang:change", (event, lang) => {
  // 通知所有窗口同步更改语言
  for (const currentWin of BrowserWindow.getAllWindows()) {
    const webContentsId = currentWin.webContents.id;
    // 这里排除掉发送通知的窗口
    if (webContentsId !== event.sender.id && !currentWin.isDestroyed) {
      currentWin.webContents.send("lang:change", lang);
    }
  }
});


app.whenReady().then(createWindow);
